package com.flashcash.kotlin.fragment.certfication

import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.CustomListener
import com.bigkoo.pickerview.view.TimePickerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.GlideDrawable
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.flashcash.kotlin.activity.BackPressListener
import com.flashcash.kotlin.data.FileType
import com.flashcash.kotlin.data.OcrResultBean
import com.flashcash.kotlin.fragment.OnInfoAdapterItemClickListener
import com.flashcash.kotlin.utils.FirebaseAnalyticsConstants
import com.flashcash.kotlin.utils.FirebaseAnalyticsUtils
import com.flashcash.kotlin.utils.adjustImg
import com.flashcash.kotlin.utils.tokenInstance
import com.flashcash.kotlin.widget.LocalButton
import com.flashcash.solu.BuildConfig
import com.flashcash.solu.R
import com.flashcash.solu.app.base.BaseFragment
import com.flashcash.solu.app.base.BaseFragmentView
import com.flashcash.solu.app.base.presenter.BaseFragmentPresenter
import com.flashcash.solu.app.base.presenter.BaseFragmentPresenterImpl
import com.flashcash.solu.bean.*
import com.flashcash.solu.common.EventCollection
import com.flashcash.solu.common.FieldParams
import com.flashcash.solu.common.FieldParamsInt
import com.flashcash.solu.common.TokenManager
import com.flashcash.solu.common.adapter.InfoAdapter
import com.flashcash.solu.common.adapter.InfoAdapterEnum
import com.flashcash.solu.common.network.FileUploadUtil
import com.flashcash.solu.utils.A2bigA
import com.flashcash.solu.utils.ACache
import com.flashcash.solu.utils.DensityUtils
import com.flashcash.solu.view.camera.TakePhotoActivity
import com.flashcash.solu.view.certification.ExampleActivity
import com.flashcash.solu.view.certification.PersonalInfoActivity
import com.flashcash.solu.view.certification.status.CardTypeStatus
import com.flashcash.solu.view.certification.status.GenderStatus
import com.flashcash.solu.view.certification.status.InfoType
import com.flashcash.solu.widget.MyEditTextView
import com.flashcash.solu.widget.SelectView
import com.flashcash.solu.widget.selfdefdialog.DialogManager
import com.flashcash.solu.widget.xleotoast.XLeoToast
import com.google.gson.Gson
import com.hwangjr.rxbus.annotation.Subscribe
import com.jakewharton.rxbinding.widget.RxTextView
import com.x.leo.apphelper.data.cache.CacheDataManage
import com.x.leo.apphelper.log.XLog
import okhttp3.ResponseBody
import org.jetbrains.anko.find
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.support.v4.toast
import retrofit2.Call
import retrofit2.Response
import retrofit2.adapter.rxjava.HttpException
import rx.Observable
import rx.Subscriber
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.io.FileInputStream
import java.util.*
import java.util.regex.Pattern

/**
 * Created by XLEO on 2018/1/18.
 */
class IdentifyFragment : BaseFragment<IdentifyFraPresenter>(), IdentifyFraView, BackPressListener {
    override fun onBackPressed() {

        if (localInputExist() && !identicalToServer()) {

            saveLocalInput()

            toast(this.getString(R.string.change_not_upload))
        } else {
            removeAllLocal()
        }
    }

    companion object {
        private const val SAVE_INSTANCE_IS_EDITABLE = "save_instance_is_editable"
        const val EXAMPLE_REQUEST_CODE = 600
    }

    private var isEditable: Boolean = false

    private var startLoadImg: Boolean = false

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putBoolean(SAVE_INSTANCE_IS_EDITABLE, isEditable)
        Log.i("IdentifyFragment", "onSaveInstanceState isEditable = $isEditable")
    }

    var dialogPlus: Dialog? = null
    private lateinit var example: TextView
    private lateinit var imgKtp: ImageView
    private lateinit var imgKtpBehind: ImageView
    //    private lateinit var etFullName: LocalEditText
    private lateinit var etFirstName: MyEditTextView
    private lateinit var etMiddleName: MyEditTextView
    private lateinit var etLastName: MyEditTextView
    private lateinit var svBirthday: SelectView
    //    private lateinit var etBirthdayLinearLayout: LinearLayout
    private lateinit var pvTime: TimePickerView
    private lateinit var etKtpNo: MyEditTextView
    lateinit var tvGender: SelectView
    lateinit var tvCardType: SelectView
    private lateinit var datePickerParent: LinearLayout
    private lateinit var btnSubmit: LocalButton
    private var gender: String? = null
    private var cardType: String? = null

    private var startLoadImgKtp: Boolean = false
    private var startLoadImgKtpBehind: Boolean = false

    override fun onObtainSuccess(identifyBean: Pair<RecordFilesResponse, PersonalInfoServerBean?>?) {
        initInputFromServer(identifyBean?.second)

        val filesBeanList = identifyBean?.first?.files
        if (filesBeanList != null && !filesBeanList.isEmpty()) {
            for (i in 0 until filesBeanList.size) {
                if (FileType.KTP_PHOTO.name == filesBeanList[i].fileType) {
                    startLoadImgKtp = true
                    loadImgWithGlide(filesBeanList[i].url, imgKtp, isImgKtpUploaded, object : OnGlideLoadImgListener {
                        override fun onLoadImgWithGlideSuccess() {
                            startLoadImgKtp = false
                        }

                        override fun onLoadImgWithGlideError() {
                            startLoadImgKtp = false
                        }

                    })
                }

                if (FileType.KTP_PHOTO_2.name == filesBeanList[i].fileType) {
                    startLoadImgKtpBehind = true
                    loadImgWithGlide(filesBeanList[i].url, imgKtpBehind, isImgKtpBehindUploaded, object : OnGlideLoadImgListener {
                        override fun onLoadImgWithGlideSuccess() {
                            startLoadImgKtpBehind = false
                        }

                        override fun onLoadImgWithGlideError() {
                            startLoadImgKtpBehind = false
                        }

                    })
                }
            }
        }
    }

    override fun onObtainError(p0: Throwable?) {
        AlertDialog.Builder(context)
                .setTitle(R.string.tips_title)
                .setMessage(R.string.error_occured)
                .setPositiveButton(R.string.retry) { dialog, _ ->
                    dialog.dismiss()
                    mPresenter.obtainIdentifyInfo()
                }
                .setNegativeButton(R.string.text_cancel) { dialog, _ ->
                    dialog.dismiss()
                }
                .create()
                .show()
    }

    override fun onOcrError(message: String?) {
        AlertDialog.Builder(context)
                .setTitle(R.string.tips_title)
                .setMessage(message ?: getString(R.string.error_occured))
                .setPositiveButton(R.string.button_ok) { dialog, _ ->
                    dialog.dismiss()
                }
                .create()
                .show()
    }

    override fun onUploadImgFail(photoInfo: PhotoInfo) {
        isImgKtpUploaded.updateValue(false)

        AlertDialog.Builder(context)
                .setTitle(R.string.tips_title)
                .setMessage(R.string.error_occured)
                .setPositiveButton(R.string.retry) { dialog, _ ->
                    dialog.dismiss()
                    mPresenter.uploadKtpImg(photoInfo)
                }
                .setNegativeButton(R.string.text_cancel) { dialog, _ ->
                    dialog.dismiss()
                }
                .create()
                .show()
    }

    override fun onUploadImgSuccess(orcResult: OcrResultBean.ResultData?) {
        isImgKtpUploaded.updateValue(true)

        etKtpNo.text = orcResult?.idNumber
//        etFullName.setText(orcResult?.name)
    }

    override fun onUploadKtpBehindImgSuccess() {
        isImgKtpBehindUploaded.updateValue(true)
    }

//    private fun getSecretName(name: String): String {
//        if (name.isEmpty()) {
//            return ""
//        }
//        val array = name.toCharArray()
//        array[0] = '*'
//        return String(array)
//    }

//    private fun getSecretKtp(ktp: String): String {
//        if (ktp.isEmpty() || ktp.length <= 8) {
//            return ""
//        }
//        val array = ktp.toCharArray()
//        var index = 0
//        while (index++ < array.size) {
//            if (index >= 4 && index < array.size - 4) {
//                array[index] = '*'
//            }
//        }
//        return String(array)
//    }

    override fun onUploadKtpBehindImgFail(photoInfo: PhotoInfo) {
        isImgKtpBehindUploaded.updateValue(false)

        AlertDialog.Builder(context)
                .setTitle(R.string.tips_title)
                .setMessage(R.string.error_occured)
                .setPositiveButton(R.string.retry) { dialog, _ ->
                    dialog.dismiss()
                    mPresenter.uploadKtpBehindImg(photoInfo)
                }
                .setNegativeButton(R.string.text_cancel) { dialog, _ ->
                    dialog.dismiss()
                }
                .create()
                .show()
    }

    private var aCache: ACache? = null
    override fun onSubmitSuccess() {
        if (isAdded) {
            //本地标记第一步是否完成
            aCache = ACache.get(context)
            aCache?.put(FieldParams.ACacheKeys.ACACHE_FINISH_IDENTIFY, "1")

            mActivity.setResult(Activity.RESULT_OK)
            val intent = Intent(context, PersonalInfoActivity::class.java)
            intent.putExtra(FieldParams.NOT_FINISH_CERTIFY, notFinish)
            mActivity.startActivity(intent)
            if (!notFinish) {
                mActivity.finish()
            }

            saveLocalInput()
        }
    }

    private fun loadImgWithGlide(url: String, imageView: ImageView, isImgUploaded: DataObserable<Boolean>, onGlideLoadImgListener: OnGlideLoadImgListener) {
        Glide.with(context)
                .load(url).listener(object : RequestListener<String, GlideDrawable> {
                    override fun onException(e: java.lang.Exception?, model: String?, target: Target<GlideDrawable>?, isFirstResource: Boolean): Boolean {
                        onGlideLoadImgListener.onLoadImgWithGlideError()
                        return false
                    }

                    override fun onResourceReady(resource: GlideDrawable?, model: String?, target: Target<GlideDrawable>?, isFromMemoryCache: Boolean, isFirstResource: Boolean): Boolean {
                        onGlideLoadImgListener.onLoadImgWithGlideSuccess()
                        return false
                    }
                })
                .placeholder(R.drawable.loading_rotate)
                .error(R.drawable.error_page)
                .into(imageView)
        isImgUploaded.updateValue(true)
    }

    interface OnGlideLoadImgListener {
        fun onLoadImgWithGlideSuccess()
        fun onLoadImgWithGlideError()
    }

    override fun initPresenter(): IdentifyFraPresenter {
        return IdentifyFraPreImpl()
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_identify
    }

    private lateinit var selectedDate: Calendar
    private lateinit var startDate: Calendar
    private lateinit var selectedDateNow: Calendar

    @SuppressLint("ResourceType")
    override fun initView(view: View?, savedInstanceState: Bundle?) {
        FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.EXPOSURE_IDENTITY_INFO, null)

        com.hwangjr.rxbus.RxBus.get().register(this)
        isEditable = CacheDataManage.obtainData(FieldParamsInt.INFO_EDITABLE, Boolean::class.java) == true
        savedInstanceState?.apply {
            isEditable = get(SAVE_INSTANCE_IS_EDITABLE) as Boolean? == true
            if (isEditable) {
                CacheDataManage.addData(FieldParamsInt.INFO_EDITABLE, isEditable)
            }
        }
        if (BuildConfig.DEBUG) {
            Log.i("IdentifyFragment", "initView isEditable = $isEditable")
        }
        if (!isEditable) {
            AlertDialog.Builder(context)
                    .setTitle(R.string.tips_title)
                    .setMessage(R.string.cannot_edit_now)
                    .setPositiveButton(R.string.button_ok) { dialog, _ ->
                        dialog.dismiss()
                    }
                    .create()
                    .show()
        }

        example = view!!.find(R.id.tv_show_id_sample)

        example.onClick {
            FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.BTN_IDENTITY_INFO_EDIT, null)
            if (!startLoadImgKtp) {
                activity!!.startActivityForResult(Intent(activity, ExampleActivity::class.java), EXAMPLE_REQUEST_CODE)
                FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.IDENTITY_ID_EXAMPLE, null)
            }
        }

        imgKtp = view.find(R.id.ktp)
        imgKtp.onClick {
            FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.IDENTITY_ID_PHOTO, null)
            openCamera()
        }
        imgKtp.isClickable = isEditable

        imgKtpBehind = view.find(R.id.ktp_behind)
        imgKtpBehind.onClick {
            if (!startLoadImgKtpBehind) {
                takePhotoKTPBehind(FileType.KTP_PHOTO_2)
            }
        }
        imgKtp.isClickable = isEditable

//        etFullName = view!!.find(R.id.et_fullname)
//        etFullName.isEnabled = isEditable

        etFirstName = view.find(R.id.et_firstname)
        etFirstName.setMyTransformationMethod(A2bigA())
        etFirstName.isEnabled = isEditable
        etFirstName.setItemOnClickListener {
            Log.d("onClick", "test")
            FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.IDENTITY_ID_FIRSTNAME, null)
            val imm: InputMethodManager = activity!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(etFirstName.editText, 0)
        }

        etMiddleName = view.find(R.id.et_middlename)
        etMiddleName.setMyTransformationMethod(A2bigA())
        etMiddleName.isEnabled = isEditable
        etMiddleName.setItemOnClickListener {
            //            activity!!.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
            FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.IDENTITY_ID_MIDDLENAME, null)
            val imm: InputMethodManager = activity!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(etMiddleName.editText, 0)
        }

        etLastName = view.find(R.id.et_lastname)
        etLastName.setMyTransformationMethod(A2bigA())
        etLastName.isEnabled = isEditable
        etLastName.setItemOnClickListener {
            //            activity!!.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
            FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.IDENTITY_ID_LASTNAME, null)
            val imm: InputMethodManager = activity!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(etLastName.editText, 0)
        }

        svBirthday = view.find(R.id.tv_birthday)
        svBirthday.isEnabled = isEditable
        svBirthday.isFocusable = false
        svBirthday.isFocusableInTouchMode = false

        datePickerParent = view.find(R.id.content)

        //以下日期控件优化
        selectedDate = Calendar.getInstance()
        startDate = Calendar.getInstance()
        selectedDate.set(1990, 0, 1)
        startDate.set(1900, 0, 1)
        pvTime = TimePickerBuilder(context
        ) { date: Date, view: View? ->
            selectedDateNow = Calendar.getInstance()
            selectedDateNow.time = date
            var yearStr: String = selectedDateNow.get(Calendar.YEAR).toString()
            var monthStr: String
            var monthOfYearRight = selectedDateNow.get(Calendar.MONTH).plus(1)
            if (monthOfYearRight > 9) {
                monthStr = monthOfYearRight.toString()
            } else {
                monthStr = "0" + monthOfYearRight.toString()
            }
            var dayOfMonthStr: String
            if (selectedDateNow.get(Calendar.DATE) > 9) {
                dayOfMonthStr = selectedDateNow.get(Calendar.DATE).toString()
            } else {
                dayOfMonthStr = "0" + selectedDateNow.get(Calendar.DATE).toString()
            }
            var birthdayStr = yearStr + "-" + monthStr + "-" + dayOfMonthStr
//            svBirthday.setText(birthdayStr.toCharArray(), 0, birthdayStr.length)
            svBirthday.text = birthdayStr
        }
                .setLayoutRes(R.layout.pickerview_custom_time, CustomListener { v ->
                    val tvSubmit = v.findViewById<View>(R.id.tv_finish) as TextView
                    val tvCancel = v.findViewById<View>(R.id.iv_cancel) as TextView
                    tvSubmit.setOnClickListener {
                        pvTime.returnData()
                        pvTime.dismiss()
                    }
                    tvCancel.setOnClickListener {
                        pvTime.dismiss()
                    }
                })
                .setLabel("", "", "",
                        "", "", "")
                .setDividerColor(ContextCompat.getColor(this.activity!!.applicationContext, R.color.line_color))//分隔线颜色
                .setContentTextSize(DensityUtils.sp2px(activity, 10))//文字大小
                .setTextColorCenter(ContextCompat.getColor(this.activity!!.applicationContext, R.color.theme_grey))//选中颜色大小
                .setTextColorOut(ContextCompat.getColor(this.activity!!.applicationContext, R.color.theme_FFBBBBBB))//未选中颜色大小
                .setDate(selectedDate)//如果不设置的话，默认是系统时间
                .setRangDate(startDate, Calendar.getInstance())//起始终止年月日设定
//                .setDecorView(datePickerParent)//消除虚拟按键遮挡
                .setTextXOffset(0, 0, 0, 0, 0, 0)//去掉3D效果
                .setLineSpacingMultiplier(1.3f)//设置高度
                .build()
        //以上日期控件优化

//        etBirthdayLinearLayout = view!!.find(R.id.et_birthday_linear_layout)
        svBirthday.setItemOnClickListener {
            pvTime.show()
        }
        svBirthday.onClick {
            FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.IDENTITY_ID_BIRTHDAY, null)
            pvTime.show()
        }

        etKtpNo = view.find(R.id.et_ktp)
        etKtpNo.isEnabled = isEditable
        etKtpNo.setItemOnClickListener {
            //            activity!!.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
            val imm: InputMethodManager = activity!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(etKtpNo.editText, 0)
            FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.IDENTITY_ID_NUMBER, null)
        }

        tvGender = view.find(R.id.tv_gender)

        tvCardType = view.find(R.id.tv_crd_type)

        btnSubmit = view.find(R.id.btn_submit)
        btnSubmit.onClick {
            FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.BTN_IDENTITY_INFO_SUBMIT, null)
            val rUMID = "^(\\d{12})$"
            val rTIN = "^(\\d{9}|\\d{12}|\\d{14})$"
            val rDRIVERLICENSE = "^(\\d{10})$"
            val rPASSPORT = "^(\\w{9})$"
            val rGSIS_STUDENT_OTHERS = "^(\\w{7,})$"
            val rph = "^(\\d{12})$"
            Log.v("cardType", cardType)
            Log.v("cardType", etKtpNo.text.toString())
            if (cardType == "UMID") {
                if (!Pattern.compile(rUMID).matcher(etKtpNo.text.toString()).matches()) {
                    XLeoToast.showMessage(R.string.ktp_no_illegality_with_num)
                } else {
//                    Log.v("cardType", "liu11111true")
                    submitData()
                }
            }

            if (cardType == "TIN") {
                if (!Pattern.compile(rTIN).matcher(etKtpNo.text.toString()).matches()) {
                    XLeoToast.showMessage(R.string.ktp_no_illegality_with_num)
                } else {
//                    Log.v("cardType", "liu11111true")
                    submitData()
                }
            }

            if (cardType == "SSS" || cardType == "DRIVERLICENSE") {
                if (!Pattern.compile(rDRIVERLICENSE).matcher(etKtpNo.text.toString()).matches()) {
                    XLeoToast.showMessage(R.string.ktp_no_illegality_with_num)
                } else {
//                    Log.v("cardType", "liu11111true")
                    submitData()
                }
            }

            if (cardType == "PASSPORT") {
                if (!Pattern.compile(rPASSPORT).matcher(etKtpNo.text.toString()).matches()) {
                    XLeoToast.showMessage(R.string.ktp_no_illegality)
                } else {
//                    Log.v("cardType", "liu11111true")
                    submitData()
                }
            }
//change
            if (cardType == "PHILHEALTH") {
                if (!Pattern.compile(rph).matcher(etKtpNo.text.toString()).matches()) {
                    XLeoToast.showMessage(R.string.ktp_no_illegality_with_num)
                } else {
//                    Log.v("cardType", "liu11111true")
                    submitData()
                }
            }

            if (cardType == "GSIS" || cardType == "STUDENT" || cardType == "OTHERS") {
                if (!Pattern.compile(rGSIS_STUDENT_OTHERS).matcher(etKtpNo.text.toString()).matches()) {
                    XLeoToast.showMessage(R.string.ktp_no_illegality)
                } else {
//                    Log.v("cardType", "liu11111true")
                    submitData()
                }
            }


            //submitData()

        }

        btnSubmit.setOnTouchListener { v, event ->
            if (!v.isClickable) {
                val str = checkUnFillContent()
                if (!TextUtils.isEmpty(str)) {
                    str?.let {
                        Toast.makeText(context, str, Toast.LENGTH_SHORT).show()
                    }
                }
            }
            return@setOnTouchListener false
        }

        btnSubmit.isClickable = false
        btnSubmit.isSelected = true

        //TODO 这里可能会有修改
        tvGender.apply {
            onClick {
                FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.IDENTITY_ID_GENDAR, null)
                setGender()
            }
            isClickable = isEditable
        }

        tvCardType.apply {
            onClick {
                FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.IDENTITY_ID_TYPE, null)
                setCardType()
            }
            isClickable = isEditable
        }
        /*view.find<LinearLayout>(R.id.ll_gender).apply {
            onClick {
                setGender()
            }
            isClickable = isEditable
        }

        view.find<LinearLayout>(R.id.ll_card_type).apply {
            onClick {
                setCardType()
            }
            isClickable = isEditable
        }*/


//        view!!.find<LinearLayout>(R.id.ll_name).onTouch { _, _ -> etFullName.requestFocus() }
//        view!!.find<LinearLayout>(R.id.ll_ktp).onTouch { _, _ -> etKtpNo.requestFocus() }

        addContentObservers()
    }

    @Subscribe
    fun onFinish(event: EventCollection.FirstFinishCertifyEvent) {
        baseActivity.finish()
    }

    fun openCamera() {
        Log.d("test", "openCamera,startLoadImgKtp:$startLoadImgKtp")
        if (!startLoadImgKtp) {
            takePhotoKTP(FileType.KTP_PHOTO)
        }
    }

    private fun submitData() {
        FirebaseAnalyticsUtils.logEvent(FirebaseAnalyticsConstants.Event.BTN_IDENTITY_INFO_EDIT, null)
        mPresenter.submitIdentifyInfo(etFirstName.text.toString(), etMiddleName.text.toString(),
                etLastName.text.toString(), svBirthday.text.toString(), etKtpNo.text.toString(),
                gender!!, tvCardType.text.toString())
    }

    override fun onDestroyView() {
        super.onDestroyView()
        com.hwangjr.rxbus.RxBus.get().unregister(this)
    }

    private fun takePhotoKTP(fileType: FileType) {
        /*val dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_take_id_photo, null)
        val confirmDialog = DialogManager.newDialog(context, dialogView, true)
        dialogView.findViewById<LocalButton>(R.id.btn_ok).onClick {
            confirmDialog?.dismiss()
            TakePhotoActivity.actionStart(mActivity, fileType)
        }
        confirmDialog.show()*/
        TakePhotoActivity.actionStart(mActivity, fileType)
    }

    private fun takePhotoKTPBehind(fileType: FileType) {
        val dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_take_id_photo_behind, null)
        val confirmDialog = DialogManager.newDialog(context, dialogView, true)
        dialogView.findViewById<LocalButton>(R.id.btn_ok).onClick {
            confirmDialog?.dismiss()
            TakePhotoActivity.actionStart(mActivity, fileType)
        }
        confirmDialog.show()
    }

    @Subscribe
    fun onPhotoTaken(photoInfo: PhotoInfo) {
        if (FileType.KTP_PHOTO.ordinal == photoInfo.fileType.ordinal) {
            adjustImgAndSet(photoInfo, imgKtp)

            mPresenter.uploadKtpImg(photoInfo)
        } else if (FileType.KTP_PHOTO_2.ordinal == photoInfo.fileType.ordinal) {
            adjustImgAndSet(photoInfo, imgKtpBehind)

            mPresenter.uploadKtpBehindImg(photoInfo)
        }
    }

    private fun adjustImgAndSet(photoInfo: PhotoInfo, imageView: ImageView) {
        Observable.create<Bitmap> {
            try {
                it.onNext(
                        adjustImg(BitmapFactory.decodeStream(FileInputStream(photoInfo.mFile)), imageView.width, imageView.height)
                )
            } catch (e: Exception) {
                it.onError(e)
            }
        }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Subscriber<Bitmap>() {
                    override fun onCompleted() {
                    }

                    override fun onError(t: Throwable?) {
                        t?.printStackTrace()
                        XLog.i("error happen" + t?.message, 10)
                        XLeoToast.showMessage(R.string.error_occured)
                    }

                    override fun onNext(bitmap: Bitmap?) {
                        if (bitmap != null) {
                            imageView.setImageBitmap(bitmap)
                        } else {
                            onError(Exception())
                        }
                    }

                })
    }

    var isImgKtpUploaded: DataObserable<Boolean> = DataObserable()
    var isImgKtpBehindUploaded: DataObserable<Boolean> = DataObserable()

    private fun addContentObservers() {
        val imageKtpObservable: Observable<Boolean> = Observable.create {
            isImgKtpUploaded.addDataChangeListener(object : DataObserable.DataChangeListener<Boolean> {
                override fun onDataChange(t: Boolean?) {
                    it.onNext(t)
                }
            })
        }

        val imageKtpBehindObservable: Observable<Boolean> = Observable.create {
            isImgKtpBehindUploaded.addDataChangeListener(object : DataObserable.DataChangeListener<Boolean> {
                override fun onDataChange(t: Boolean?) {
                    it.onNext(t)
                }
            })
        }

        //菲律宾不需要身份证背面
        Observable.combineLatest(
                RxTextView.textChanges(etFirstName.editText),
                RxTextView.textChanges(etMiddleName.editText),
                RxTextView.textChanges(etLastName.editText),
                RxTextView.textChanges(svBirthday.textView),
                RxTextView.textChanges(etKtpNo.editText),
                RxTextView.textChanges(tvGender.textView),
                RxTextView.textChanges(tvCardType.textView),
                imageKtpObservable
        ) { firstName, middleName, lastName, birthday, _, charSequence1, charSequence2, isKtpUploaded ->
            isEditable && etKtpNo.checkLegal()
                    && TextUtils.getTrimmedLength(firstName) > 0
                    && etFirstName.checkLegal()
//                    && TextUtils.getTrimmedLength(middleName) > 0
                    && (TextUtils.isEmpty(etMiddleName.text) || etMiddleName.checkLegal())
                    && TextUtils.getTrimmedLength(lastName) > 0
                    && etLastName.checkLegal()
                    && TextUtils.getTrimmedLength(birthday) > 0
                    && !TextUtils.isEmpty(charSequence1)
                    && !TextUtils.isEmpty(charSequence2)
                    && isKtpUploaded
        }.subscribe {
            btnSubmit.isClickable = it
            btnSubmit.isSelected = !it
        }

    }

    private fun setGender() {
        val genderAdapter = getGenderAdapter() as InfoAdapterEnum
        if (dialogPlus != null && dialogPlus!!.isShowing) {
            dialogPlus?.dismiss()
        }
        dialogPlus = DialogManager.newListViewDialog(context)
                .setAdapter(genderAdapter)
                .setExpanded(false)
                .setGravity(Gravity.CENTER)
                .create()
        dialogPlus?.show()
    }

    private fun setCardType() {
        val cardTypeAdapter = getCardTypeAdapter() as InfoAdapterEnum
        if (dialogPlus != null && dialogPlus!!.isShowing) {
            dialogPlus?.dismiss()
        }
        dialogPlus = DialogManager.newListViewDialog(context)
                .setAdapter(cardTypeAdapter)
                .setExpanded(false)
                .setGravity(Gravity.CENTER)
                .create()
        dialogPlus?.show()
    }

    fun getGenderAdapter(): InfoAdapter {
        val genderAdapter = InfoAdapterEnum(context)
        genderAdapter.addItem(GenderStatus.MALE, InfoType.GENDER)
        genderAdapter.addItem(GenderStatus.FEMALE, InfoType.GENDER)
        genderAdapter.setOnItemClickListener(object : OnInfoAdapterItemClickListener {
            override fun onItemClick(data: InfoAdapter.InfoItem) {
                if (dialogPlus != null && dialogPlus!!.isShowing) {
                    dialogPlus?.dismiss()
                }
                tvGender.text = data.infoStr
                gender = data.valueStr

                val key = FieldParams.PersonInfo.GENDER + TokenManager.getInstance().mobile
                ACache.get(mActivity).put(key, gender)
            }
        })
        return genderAdapter
    }

    private var mIDTypes = ArrayList<IDType>()
    override fun initIDTypeArray(t: ArrayList<IDType>?) {
        mIDTypes = t!!
    }

    fun getCardTypeAdapter(): InfoAdapter {
        val cardTypeAdapter = InfoAdapterEnum(context)
        /*cardTypeAdapter.addItem(CardTypeStatus.UMID, InfoType.CARDTYPE)
        cardTypeAdapter.addItem(CardTypeStatus.SSS, InfoType.CARDTYPE)
        cardTypeAdapter.addItem(CardTypeStatus.DRIVERLICENSE, InfoType.CARDTYPE)
        cardTypeAdapter.addItem(CardTypeStatus.PASSPORT, InfoType.CARDTYPE)
        cardTypeAdapter.addItem(CardTypeStatus.GSIS, InfoType.CARDTYPE)
        cardTypeAdapter.addItem(CardTypeStatus.STUDENT, InfoType.CARDTYPE)
        cardTypeAdapter.addItem(CardTypeStatus.TIN, InfoType.CARDTYPE)
        cardTypeAdapter.addItem(CardTypeStatus.OTHERS, InfoType.CARDTYPE)*/
        mIDTypes.forEach { idType ->
            when (idType.code) {
                CardTypeStatus.UMID.value -> cardTypeAdapter.addItem(CardTypeStatus.UMID, InfoType.CARDTYPE)
                CardTypeStatus.SSS.value -> cardTypeAdapter.addItem(CardTypeStatus.SSS, InfoType.CARDTYPE)
                CardTypeStatus.DRIVERLICENSE.value -> cardTypeAdapter.addItem(CardTypeStatus.DRIVERLICENSE, InfoType.CARDTYPE)
                CardTypeStatus.PASSPORT.value -> cardTypeAdapter.addItem(CardTypeStatus.PASSPORT, InfoType.CARDTYPE)
                CardTypeStatus.GSIS.value -> cardTypeAdapter.addItem(CardTypeStatus.GSIS, InfoType.CARDTYPE)
                CardTypeStatus.STUDENT.value -> cardTypeAdapter.addItem(CardTypeStatus.STUDENT, InfoType.CARDTYPE)
                CardTypeStatus.TIN.value -> cardTypeAdapter.addItem(CardTypeStatus.TIN, InfoType.CARDTYPE)
                CardTypeStatus.OTHERS.value -> cardTypeAdapter.addItem(CardTypeStatus.OTHERS, InfoType.CARDTYPE)
                CardTypeStatus.PHIHEALTH.value -> cardTypeAdapter.addItem(CardTypeStatus.PHIHEALTH, InfoType.CARDTYPE)
                CardTypeStatus.PHILHEALTH.value -> cardTypeAdapter.addItem(CardTypeStatus.PHILHEALTH, InfoType.CARDTYPE)
            }
        }

//
//        cardTypeAdapter.addItem(CardTypeStatus.PHIHEALTH, InfoType.CARDTYPE)
//        cardTypeAdapter.addItem(CardTypeStatus.NBI, InfoType.CARDTYPE)
//        cardTypeAdapter.addItem(CardTypeStatus.PRC, InfoType.CARDTYPE)
//

        cardTypeAdapter.setOnItemClickListener(object : OnInfoAdapterItemClickListener {
            override fun onItemClick(data: InfoAdapter.InfoItem) {
                if (dialogPlus != null && dialogPlus!!.isShowing) {
                    dialogPlus?.dismiss()
                }
                tvCardType.text = data.infoStr
                cardType = data.valueStr

                Log.i("car11dType", cardType)

                val key = FieldParams.PersonInfo.CARDTYPE + TokenManager.getInstance().mobile
                ACache.get(mActivity).put(key, cardType)
            }
        })
        return cardTypeAdapter
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            if (mActivity.intent.getBooleanExtra(FieldParams.NEED_OBTAIN_DATA, false)) {
                mPresenter.obtainIdentifyInfo()
            }
        }
    }

    var fromSplash: Boolean = false
    var notFinish: Boolean = false
    override fun initData() {
        initByLocal()
        mPresenter.getIDTypeArray()

        if (mActivity.intent.getBooleanExtra(FieldParams.NEED_OBTAIN_DATA, false)) {
            mPresenter.obtainIdentifyInfo()
        }
        if (mActivity.intent.getBooleanExtra(FieldParams.FROM_SPLASH, false)) {
            fromSplash = true
        }
        if (mActivity.intent.getBooleanExtra(FieldParams.NOT_FINISH_CERTIFY, false)) {
            notFinish = true
        }
    }


    private fun initByLocal() {
//        val fullName = ACache.get(mActivity).getAsString(getSaveKey(FieldParams.PersonInfo.FULLNAME))
        val firstName = ACache.get(mActivity).getAsString(getSaveKey(FieldParams.PersonInfo.FIRSTNAME))
        val middleName = ACache.get(mActivity).getAsString(getSaveKey(FieldParams.PersonInfo.MIDDLENAME))
        val lastName = ACache.get(mActivity).getAsString(getSaveKey(FieldParams.PersonInfo.LASTNAME))
        val birthday = ACache.get(mActivity).getAsString(getSaveKey(FieldParams.PersonInfo.BIRTHDAY))
        val ktpnoT = ACache.get(mActivity).getAsString(getSaveKey(FieldParams.PersonInfo.KTP_NO))
        gender = ACache.get(mActivity).getAsString(getSaveKey(FieldParams.PersonInfo.GENDER))
        cardType = ACache.get(mActivity).getAsString(getSaveKey(FieldParams.PersonInfo.CARDTYPE))

//        if (!TextUtils.isEmpty(fullName)) {
//            etFullName.setText(getSecretName(fullName))
//        }

        if (!TextUtils.isEmpty(firstName)) {
            etFirstName.text = firstName
        }

        if (!TextUtils.isEmpty(middleName)) {
            etMiddleName.text = middleName
        }

        if (!TextUtils.isEmpty(lastName)) {
            etLastName.text = lastName
        }

        if (!TextUtils.isEmpty(birthday)) {
            svBirthday.text = birthday
        }

        if (!TextUtils.isEmpty(ktpnoT)) {
            etKtpNo.text = ktpnoT
        }

        if (!TextUtils.isEmpty(gender)) {
            tvGender.setText(getString(GenderStatus.valueOf(gender!!).showString))
        }

        if (!TextUtils.isEmpty(cardType)) {
            tvCardType.text = getString(CardTypeStatus.valueOf(cardType!!).showString)
        }
    }

    var mServerInfo: PersonalInfoServerBean? = null
    private fun initInputFromServer(infoFromServer: PersonalInfoServerBean?) {

        if (infoFromServer != null) {
            mServerInfo = infoFromServer

            val cache = ACache.get(this.baseActivity)
//            val fullName: String? = cache.getAsString(getSaveKey(FieldParams.PersonInfo.FULLNAME))
            val firstName: String? = cache.getAsString(getSaveKey(FieldParams.PersonInfo.FIRSTNAME))
            val middleName: String? = cache.getAsString(getSaveKey(FieldParams.PersonInfo.MIDDLENAME))
            val lastName: String? = cache.getAsString(getSaveKey(FieldParams.PersonInfo.LASTNAME))
            val birthday: String? = cache.getAsString(getSaveKey(FieldParams.PersonInfo.BIRTHDAY))
            val ktpNo: String? = cache.getAsString(getSaveKey(FieldParams.PersonInfo.KTP_NO))
            gender = cache.getAsString(getSaveKey(FieldParams.PersonInfo.GENDER))
            cardType = cache.getAsString(getSaveKey(FieldParams.PersonInfo.CARDTYPE))

//            if (!TextUtils.isEmpty(fullName)) {
//                etFullName.setText(fullName)
//            } else {
//                etFullName.setText(infoFromServer.fullName)
//            }

            if (!TextUtils.isEmpty(firstName)) {
                etFirstName.text = firstName
            } else {
                if (!TextUtils.isEmpty(infoFromServer.firstName)) {
                    etFirstName.text = infoFromServer.firstName
                }
            }

            if (!TextUtils.isEmpty(middleName)) {
                etMiddleName.text = middleName
            } else {
                if (!TextUtils.isEmpty(infoFromServer.middleName)) {
                    etMiddleName.text = infoFromServer.middleName
                }
            }

            if (!TextUtils.isEmpty(lastName)) {
                etLastName.text = lastName
            } else {
                if (!TextUtils.isEmpty(infoFromServer.lastName)) {
                    etLastName.text = infoFromServer.lastName
                }
            }

            if (!TextUtils.isEmpty(birthday)) {
                svBirthday.text = birthday
            } else {
                svBirthday.text = infoFromServer.birthday
            }

            if (!TextUtils.isEmpty(ktpNo)) {
                etKtpNo.text = ktpNo
            } else {
                etKtpNo.text = infoFromServer.credentialNo
            }

            if (!TextUtils.isEmpty(gender)) {
                tvGender.setText(getString(GenderStatus.valueOf(gender!!).showString))
            } else {
                gender = infoFromServer.gender
                if (gender != null) {
                    tvGender.setText(getString(GenderStatus.valueOf(gender!!).showString))
                }
            }

            if (!TextUtils.isEmpty(cardType)) {
                tvCardType.text = getString(CardTypeStatus.valueOf(cardType!!).showString)
            } else {
                cardType = infoFromServer.credentialType
                if (cardType != null) {
                    tvCardType.text = getString(CardTypeStatus.valueOf(cardType!!).showString)
                }
            }
        }
    }

    private fun checkUnFillContent(): String? {
        if (!tvCardType.checkLegal()) {
            return null
        }
        if (isImgKtpUploaded.value == null || isImgKtpUploaded.value == false) {
            return getString(R.string.please_upload_ktp_photo)
        }
        //菲律宾只上传一面身份证
//        if (isImgKtpBehindUploaded.value == null || isImgKtpBehindUploaded.value == false) {
//            return getString(R.string.please_upload_ktp_behind_photo)
//        }
//        if (TextUtils.isEmpty(etFullName.text) || !etFullName.checkLegal()) {
//            return if (etFullName.text?.toString()?.length ?: 0 > 64) {
//                getString(R.string.name_too_long)
//            } else {
//                getString(R.string.enter_your_full_name)
//            }
//        }

        if (TextUtils.isEmpty(etFirstName.text)) {
//            return getString(R.string.enter_your_first_name)
            return null
        } else if (!etFirstName.checkLegal()) {
            return getString(R.string.correct_format_first_name)
        }

        if (!TextUtils.isEmpty(etMiddleName.text)) {
            return null
        } else if (!etMiddleName.checkLegal()) {
            return getString(R.string.correct_format_middle_name)
        }


        if (TextUtils.isEmpty(etLastName.text)) {
//            return getString(R.string.enter_your_last_name)
            return null
        } else if (!etLastName.checkLegal()) {
            return getString(R.string.correct_format_last_name)
        }

        if (TextUtils.isEmpty(svBirthday.text)) {
            /*return if (svBirthday.text?.toString()?.length ?: 0 > 64) {
                getString(R.string.birthday_too_long)
            } else {
                getString(R.string.enter_your_birthday)
            }*/
            return null
        } else if (!svBirthday.checkLegal()) {
            if (svBirthday.text?.toString()?.length ?: 0 > 64) {
                return getString(R.string.birthday_too_long)
            }
        }

        if (TextUtils.isEmpty(etKtpNo.text)) {
            /*return if (etKtpNo.text?.toString()?.length ?: 0 > 64) {
                getString(R.string.ktp_no_too_long)
            } else {
                getString(R.string.enter_ktp_number)
            }*/
            return null
        } else if (!etKtpNo.checkLegal() && etKtpNo.text?.toString()?.length ?: 0 > 64) {
            return getString(R.string.ktp_no_too_long)
        }
        if (!tvGender.checkLegal()) {
            return null
        }
        return null
    }

    private fun localInputExist(): Boolean {
        return !TextUtils.isEmpty(etFirstName.text.toString())
//                || !TextUtils.isEmpty(etMiddleName.text.toString())
//              || !TextUtils.isEmpty(etFullName.text.toString())
                || !TextUtils.isEmpty(etLastName.text.toString())
                || !TextUtils.isEmpty(svBirthday.text.toString())
                || !TextUtils.isEmpty(etKtpNo.text.toString())
                || !TextUtils.isEmpty(gender)
                || !TextUtils.isEmpty(cardType)
    }

    /**检查本地输入是否和服务器的相同*/
    private fun identicalToServer(): Boolean {

        //都相同，返回true
        if (mServerInfo != null) {

            val serverArr = arrayOf(mServerInfo?.firstName, mServerInfo?.middleName,
                    mServerInfo?.lastName, mServerInfo?.birthday, mServerInfo?.credentialNo, mServerInfo?.gender, mServerInfo?.credentialType)

            val localArr = getLocalInput()

            return serverArr contentEquals localArr
        }

        return false
    }

    private fun getLocalInput(): Array<String?> {
        return arrayOf(etFirstName.text.toString(),
                etMiddleName.text.toString(), etLastName.text.toString(),
                svBirthday.text.toString(), etKtpNo.text.toString(), gender, cardType)
    }

    private fun saveLocalInput() {
        val cache = ACache.get(this.baseActivity)

//        if (!TextUtils.isEmpty(etFullName.text.toString())) {
//            cache.put(getSaveKey(FieldParams.PersonInfo.FULLNAME), etFullName.text.toString())
//        } else {
//            cache.remove(getSaveKey(FieldParams.PersonInfo.FULLNAME))
//        }

        if (!TextUtils.isEmpty(etFirstName.text.toString()) &&
                !TextUtils.isEmpty(etLastName.text.toString())) {
            var fullName: String
            if (!TextUtils.isEmpty(etMiddleName.text.toString())) {
                fullName = etFirstName.text.toString() + "·" + etMiddleName.text.toString() + "·" + etLastName.text.toString()
                cache.put(getSaveKey(FieldParams.PersonInfo.FULLNAME), fullName)
            } else {
                fullName = etFirstName.text.toString() + "·" + etLastName.text.toString()
                cache.put(getSaveKey(FieldParams.PersonInfo.FULLNAME), fullName)
            }
        } else {
            cache.remove(getSaveKey(FieldParams.PersonInfo.FULLNAME))
        }

        if (!TextUtils.isEmpty(etFirstName.text.toString())) {
            cache.put(getSaveKey(FieldParams.PersonInfo.FIRSTNAME), etFirstName.text.toString())
        } else {
            cache.remove(getSaveKey(FieldParams.PersonInfo.FIRSTNAME))
        }

        if (!TextUtils.isEmpty(etMiddleName.text.toString())) {
            cache.put(getSaveKey(FieldParams.PersonInfo.MIDDLENAME), etMiddleName.text.toString())
        } else {
            cache.remove(getSaveKey(FieldParams.PersonInfo.MIDDLENAME))
        }

        if (!TextUtils.isEmpty(etLastName.text.toString())) {
            cache.put(getSaveKey(FieldParams.PersonInfo.LASTNAME), etLastName.text.toString())
        } else {
            cache.remove(getSaveKey(FieldParams.PersonInfo.LASTNAME))
        }

        if (!TextUtils.isEmpty(svBirthday.text.toString())) {
            cache.put(getSaveKey(FieldParams.PersonInfo.BIRTHDAY), svBirthday.text.toString())
        } else {
            cache.remove(getSaveKey(FieldParams.PersonInfo.BIRTHDAY))
        }

        if (!TextUtils.isEmpty(etKtpNo.text.toString())) {
            cache.put(getSaveKey(FieldParams.PersonInfo.KTP_NO), etKtpNo.text.toString())
        } else {
            cache.remove(getSaveKey(FieldParams.PersonInfo.KTP_NO))
        }

        if (!TextUtils.isEmpty(gender)) {
            cache.put(getSaveKey(FieldParams.PersonInfo.GENDER), gender)
        } else {
            cache.remove(getSaveKey(FieldParams.PersonInfo.GENDER))
        }
        if (!TextUtils.isEmpty(cardType)) {
            cache.put(getSaveKey(FieldParams.PersonInfo.CARDTYPE), cardType)
        } else {
            cache.remove(getSaveKey(FieldParams.PersonInfo.CARDTYPE))
        }

    }

    private fun removeAllLocal() {
        val cache = ACache.get(this.baseActivity)
//        cache.remove(getSaveKey(FieldParams.PersonInfo.FULLNAME))
        cache.remove(getSaveKey(FieldParams.PersonInfo.FIRSTNAME))
        cache.remove(getSaveKey(FieldParams.PersonInfo.MIDDLENAME))
        cache.remove(getSaveKey(FieldParams.PersonInfo.LASTNAME))
        cache.remove(getSaveKey(FieldParams.PersonInfo.KTP_NO))
        cache.remove(getSaveKey(FieldParams.PersonInfo.GENDER))
        cache.remove(getSaveKey(FieldParams.PersonInfo.CARDTYPE))
    }

    private fun getSaveKey(key: String): String {
        return key + TokenManager.getInstance().mobile
    }

}

class IdentifyFraPreImpl : IdentifyFraPresenter, BaseFragmentPresenterImpl() {
    override fun getIDTypeArray() {
        showLoading("")
        mUserApi.credentialTypeArray
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Subscriber<ArrayList<IDType>>() {
                    override fun onNext(t: ArrayList<IDType>?) {
                        dismissLoading()
                        if (isAttached) {
                            //todo 暂时隐藏PHILHEALTH Card类型
                            val idTypes: ArrayList<IDType> = ArrayList()
                            val itr = t!!.iterator()
                            while (itr.hasNext()) {
                                var type = itr.next()
//                                if (!TextUtils.equals(type.name, "PHILHEALTH Card")) {
                                idTypes.add(type)
//                                }
                            }
                            (mView as IdentifyFraView).initIDTypeArray(idTypes)
                        }
                    }

                    override fun onCompleted() {

                    }

                    override fun onError(e: Throwable?) {
                        dismissLoading()
                    }

                })
    }

    override fun uploadKtpImg(photoInfo: PhotoInfo) {
        showLoading("")
        FileUploadUtil.idOcr(
                photoInfo.mFile,
                TokenManager.getInstance().token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Subscriber<OcrResultBean>() {
                    override fun onNext(p0: OcrResultBean?) {
                        dismissLoading()
                        if (isAttached && p0 != null) {
                            if (TextUtils.equals("SUCCESS", p0.code)) {
                                try {
                                    val result = Gson().fromJson(p0.data, OcrResultBean.ResultData::class.java)
                                    (mView as IdentifyFraView).onUploadImgSuccess(result)
                                } catch (e: Exception) {
                                    onError(e)
                                }

                            } else {
                                (mView as IdentifyFraView).onOcrError(p0.message)
                            }
                        } else {
                            onError(Exception())
                        }
                    }

                    override fun onError(p0: Throwable?) {
                        dismissLoading()
                        if (isAttached) {
                            if (p0 != null && p0 is HttpException) {
                                try {
                                    val responseErrorBody = Gson().fromJson(p0.response()?.errorBody()?.string(), ResponseErrorBody::class.java)
                                    XLeoToast.showMessage("" + responseErrorBody?.message)
                                } catch (e: Throwable) {
                                    XLeoToast.showMessage(R.string.error_occured)
                                }
                            } else {
                                (mView as IdentifyFraView).onUploadImgFail(photoInfo)
                            }
                        }
                    }

                    override fun onCompleted() {
                    }

                })
    }

    override fun uploadKtpBehindImg(photoInfo: PhotoInfo) {
        showLoading("")
        FileUploadUtil.uploadPhotoFile(photoInfo.fileType, photoInfo.mFile, TokenManager.getInstance().token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(mView.bindToLifecycle())
                .subscribe(object : Subscriber<android.util.Pair<Call<ResponseBody>, Response<ResponseBody>>>() {
                    override fun onNext(pair: android.util.Pair<Call<ResponseBody>, Response<ResponseBody>>?) {
                        dismissLoading()
                        (mView as IdentifyFraView).onUploadKtpBehindImgSuccess()
                    }

                    override fun onCompleted() {
                    }

                    override fun onError(e: Throwable?) {
                        e?.printStackTrace()
                        dismissLoading()
                        (mView as IdentifyFraView).onUploadKtpBehindImgFail(photoInfo)
                    }
                })
    }

    override fun obtainIdentifyInfo() {
        showLoading("")
        mUserApi.recordFiles(TokenManager.getInstance().token)
                .zipWith(mUserApi.getPersonalInfo(tokenInstance.token)) { t1, t2 ->
                    Pair<RecordFilesResponse, PersonalInfoServerBean?>(t1, t2)
                }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Subscriber<Pair<RecordFilesResponse, PersonalInfoServerBean?>>() {
                    override fun onError(p0: Throwable?) {
                        dismissLoading()
                        if (isAttached) {
                            (mView as IdentifyFraView).onObtainError(p0)
                        }
                    }

                    override fun onNext(p0: Pair<RecordFilesResponse, PersonalInfoServerBean?>?) {
                        dismissLoading()
                        if (isAttached) {
                            (mView as IdentifyFraView).onObtainSuccess(p0)
                        }
                    }

                    override fun onCompleted() {
                    }

                })
    }

    override fun submitIdentifyInfo(toString1: String, toString2: String,
                                    toString3: String, toString4: String, toString5: String, gender: String, credentialType: String) {
        if (isAttached) {
            (mView as IdentifyFraView).onSubmitSuccess()
        }
    }

}

interface IdentifyFraView : BaseFragmentView {
    fun onObtainSuccess(identifyBean: Pair<RecordFilesResponse, PersonalInfoServerBean?>?)
    fun onSubmitSuccess()
    fun onUploadImgSuccess(identifyBean: OcrResultBean.ResultData?)
    fun onUploadImgFail(photoInfo: PhotoInfo)
    fun onOcrError(message: String?)
    fun onObtainError(p0: Throwable?)
    fun onUploadKtpBehindImgSuccess()
    fun onUploadKtpBehindImgFail(photoInfo: PhotoInfo)
    fun initIDTypeArray(t: ArrayList<IDType>?)
}

interface IdentifyFraPresenter : BaseFragmentPresenter {
    fun submitIdentifyInfo(toString1: String, toString2: String, toString3: String,
                           toString4: String, toString5: String, gender: String, credentialType: String)

    fun obtainIdentifyInfo()
    fun uploadKtpImg(photoInfo: PhotoInfo)
    fun uploadKtpBehindImg(photoInfo: PhotoInfo)
    fun getIDTypeArray()
}